<script>
import { page } from '@/api/question';
import { FilterMatchMode } from '@primevue/core/api';
import Button from 'primevue/button';
import InputText from 'primevue/inputtext';
import { useToast } from 'primevue/usetoast';
import Dropdown from 'primevue/dropdown';
import TreeSelect from 'primevue/treeselect';
import { listQuestionBank } from '@/api/questionBank';
import { useRouter } from 'vue-router';

export default {
    components: {
        InputText,
        Button,
        Dropdown,
        TreeSelect
    },
    data() {
        return {
            questions: [],
            question: {
                id: null,
                questionNumber: null,
                content: null,
                options: null,
                questionBankId: null,
                questionBankName: null,
                type: null,
                correctAnswer: null,
                explanation: null,
                subQuestions: null
            },
            types: [
                { label: '单选题', value: 0 },
                { label: '多选题', value: 1 }
            ],
            statuses: [
                { label: '有效', value: 1 },
                { label: '无效', value: 0 }
            ],
            selectedQuestions: null,
            deleteQuestionDialog: false,
            deleteQuestionsDialog: false,
            loading: false,
            filters: {
                global: { value: null, matchMode: FilterMatchMode.CONTAINS }
            },
            pageSize: 10,
            pageNum: 1,
            totalRecords: 0,
            searchQuery: {
                content: null,
                questionBankId: null,
                status: null,
                type: null,
                id: null,
                questionNumber: null
            },
            selectedQuestionBank: null,
            questionBanks: []
        };
    },
    mounted() {
        this.loadQuestions();
        this.loadQuestionBanks();
    },
    methods: {
        async loadQuestions() {
            this.loading = true;
            try {
                const params = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    ...this.searchQuery
                };

                const response = await page(params);

                if (response.code === 200) {
                    this.questions = response.data.list || [];
                    this.totalRecords = response.data.total || 0;
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '加载失败',
                        detail: response.message || '无法加载题目数据',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '加载失败',
                    detail: '无法加载题目数据',
                    life: 3000
                });
                console.error('加载题目失败:', error);
            } finally {
                this.loading = false;
            }
        },

        async loadQuestionBanks() {
            try {
                const response = await listQuestionBank({
                    pageNum: 1,
                    pageSize: 1000,
                    language: null
                });

                if (response.code === 200) {
                    this.questionBanks = (response.data || []).map((item) => ({
                        key: item.id.toString(),
                        label: item.name,
                        data: item.id
                    }));
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '加载失败',
                        detail: response.message || '无法加载题库数据',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '加载失败',
                    detail: '无法加载题库数据',
                    life: 3000
                });
                console.error('加载题库失败:', error);
            }
        },

        resetSearch() {
            this.searchQuery = {
                code: null,
                questionBankIds: null,
                status: null,
                createTimeRange: null
            };
            this.selectedQuestionBank = null;
            this.loadQuestions();
        },

        onPage(event) {
            this.pageNum = event.page + 1;
            this.pageSize = event.rows;
            this.loadQuestions();
        },
        onSort(event) {
            let sortField = event.sortField;
            let sortOrder = event.sortOrder;
            if (sortField) {
                this.questions.sort((a, b) => {
                    let result = 0;
                    if (a[sortField] < b[sortField]) {
                        result = -1;
                    } else if (a[sortField] > b[sortField]) {
                        result = 1;
                    }
                    return sortOrder === 1 ? result : -result;
                });
            }
        },

        performSearch() {
            this.pageNum = 1;
            this.loadQuestions();
        },

        handleQuestionBankChange(value) {
            if (value && typeof value === 'object') {
                const keys = Object.keys(value);
                if (keys.length > 0) {
                    this.searchQuery.questionBankId = parseInt(keys[0]);
                } else {
                    this.searchQuery.questionBankId = null;
                }
            } else {
                this.searchQuery.questionBankId = value;
            }
        },

        confirmDeleteQuestion(activationCode) {
            this.question = activationCode;
            this.deleteQuestionDialog = true;
        },

        async deleteQuestion() {
            try {
                this.loading = true;
                const response = await batchDelete([this.question.id]);

                if (response.code === 200) {
                    this.$toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: '题目已删除',
                        life: 3000
                    });
                    this.deleteQuestionDialog = false;
                    this.loadQuestions();
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '失败',
                        detail: response.message || '删除题目失败',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '删除题目时出错',
                    life: 3000
                });
                console.error('删除题目失败:', error);
            } finally {
                this.loading = false;
                this.deleteQuestionDialog = false;
            }
        },

        confirmDeleteSelected() {
            this.deleteQuestionsDialog = true;
        },

        async deleteSelectedQuestions() {
            try {
                this.loading = true;
                const ids = this.selectedQuestions.map((ac) => ac.id);
                const response = await batchDelete(ids);

                if (response.code === 200) {
                    this.$toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: '选中的题目已删除',
                        life: 3000
                    });
                    this.selectedQuestions = null;
                    this.deleteQuestionsDialog = false;
                    this.loadQuestions();
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '失败',
                        detail: response.message || '批量删除题目失败',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '批量删除题目时出错',
                    life: 3000
                });
                console.error('批量删除题目失败:', error);
            } finally {
                this.loading = false;
                this.deleteQuestionsDialog = false;
            }
        },

        exportCSV() {
            this.$refs.dt.exportCSV();
        },

        editQuestion(rowData) {
            this.$router.push({
                name: 'QuestionDetail',
                params: { id: rowData.id }
            });
        },

        addQuestion() {
            this.$router.push({
                name: 'QuestionDetail'
            });
        },

        stripHtml(html) {
            if (!html) return '';
            const tmp = document.createElement('div');
            tmp.innerHTML = html;
            return tmp.textContent || tmp.innerText || '';
        },
        formatOptions(options) {
            try {
                const parsedOptions = JSON.parse(options || '[]');
                return parsedOptions.map(opt => `${opt.label}: ${this.stripHtml(opt.content)}`).join('; ');
            } catch (e) {
                return '';
            }
        },
        formatDiscussions(discussions) {
            try {
                const parsedDiscussions = JSON.parse(discussions || '[]');
                return parsedDiscussions.map(d => `${d.username}: ${d.content}`).join('; ');
            } catch (e) {
                return '';
            }
        },
        getQuestionTypeLabel(type) {
            const questionType = this.types.find(t => t.value === type);
            return questionType ? questionType.label : '未知类型';
        }
    },
    setup() {
        const toast = useToast();
        const router = useRouter();
        return { toast, router };
    }
};
</script>

<template>
    <div>
        <div class="card">
            <Toast />
            <Toolbar class="mb-6">
                <template #start>
                    <Button label="批量删除" icon="pi pi-trash" severity="secondary" @click="confirmDeleteSelected" :disabled="!selectedQuestions || !selectedQuestions.length" />
                </template>
                <template #end>
                    <Button label="新建题目" icon="pi pi-plus" severity="primary" class="mr-2" @click="addQuestion" />
                    <Button label="导出" icon="pi pi-upload" severity="secondary" @click="exportCSV($event)" />
                </template>
            </Toolbar>
            <Toolbar>
                <template #start>
                    <div class="flex flex-wrap items-center gap-2">
                            <FloatLabel variant="on">
                            <InputText id="on_label" v-model="searchQuery.id"/>
                            <label for="on_label">搜索题目ID</label>
                        </FloatLabel>
                        <FloatLabel variant="on">
                            <InputText id="on_label" v-model="searchQuery.questionNumber"/>
                            <label for="on_label">搜索题目序号</label>
                        </FloatLabel>
                        <FloatLabel variant="on">
                            <InputText id="on_label" v-model="searchQuery.content"/>
                            <label for="on_label">搜索题库内容</label>
                        </FloatLabel>
                        <TreeSelect v-model="selectedQuestionBank" :options="questionBanks" selectionMode="single" placeholder="选择题库" class="mr-2 w-12rem" :filter="true" :showClear="true" @update:modelValue="handleQuestionBankChange" />
                        <Dropdown v-model="searchQuery.type" :options="types" optionLabel="label" optionValue="value" placeholder="选择题目类型" class="mr-2" :showClear="true" />
                        <Dropdown v-model="searchQuery.status" :options="statuses" optionLabel="label" optionValue="value" placeholder="选择状态" class="mr-2" :showClear="true" />
                        <Button v-if="Object.values(searchQuery).some((value) => value !== null && value !== '')" label="重置" icon="pi pi-eraser" severity="info" @click="resetSearch" color="mr-2" />
                    </div>
                </template>
                <template #end>
                    <Button label="搜索" icon="pi pi-search" @click="performSearch" />
                </template>
            </Toolbar>
            <DataTable
                ref="dt"
                stripedRows
                v-model:selection="selectedQuestions"
                :value="questions"
                dataKey="id"
                :paginator="true"
                :rows="pageSize"
                lazy
                :totalRecords="totalRecords"
                scrollable
                :loading="loading"
                @page="onPage($event)"
                @sort="onSort($event)"
                :filters="filters"
                paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                :rowsPerPageOptions="[5, 10, 20, 50]"
                currentPageReportTemplate="显示 {first} 到 {last} 共 {totalRecords} 条记录"
            >
                <template #header>
                    <h4 class="m-0">题目中心</h4>
                </template>

                <Column selectionMode="multiple" style="width: 3rem" :exportable="false"></Column>
                <Column field="id" frozen header="ID" sortable style="min-width: 5rem" bodyClass="text-center"></Column>
                <Column field="questionNumber" frozen header="序号" sortable style="min-width: 5rem" bodyClass="text-center"></Column>
                <Column field="content" frozen header="题目" sortable style="min-width: 10rem" bodyClass="text-center">
                    <template #body="{ data }">
                        <div class="text-truncate" style="max-width: 300px" :title="stripHtml(data.content)">
                            {{ stripHtml(data.content) }}
                        </div>
                    </template>
                </Column>
                <Column field="options" header="选项" sortable style="min-width: 16rem" bodyClass="text-center">
                    <template #body="{ data }">
                        <div class="text-truncate" style="max-width: 200px" :title="formatOptions(data.options)">
                            {{ formatOptions(data.options) }}
                        </div>
                    </template>
                </Column>
                <Column field="questionBankName" header="题库名称" sortable style="min-width: 16rem" bodyClass="text-center"></Column>
                <Column field="correctAnswer" header="正确答案" sortable style="min-width: 16rem" bodyClass="text-center"></Column>
                <Column field="explanation" header="解释" sortable style="min-width: 16rem" bodyClass="text-center">
                    <template #body="{ data }">
                        <div class="text-truncate" style="max-width: 200px" :title="stripHtml(data.explanation)">
                            {{ stripHtml(data.explanation) }}
                        </div>
                    </template>
                </Column>
                <Column field="discussion" header="讨论" sortable style="min-width: 16rem" bodyClass="text-center">
                    <template #body="{ data }">
                        <div class="text-truncate" style="max-width: 200px" :title="formatDiscussions(data.discussion)">
                            {{ formatDiscussions(data.discussion) }}
                        </div>
                    </template>
                </Column>
                <Column field="votedAnswer" header="投票答案" sortable style="min-width: 16rem" bodyClass="text-center"></Column>
                <Column field="status" header="类型" sortable style="min-width: 10rem" bodyClass="text-center">
                    <template #body="slotProps">
                        <Tag :severity="slotProps.data.type === 1 ? 'info' : 'secondary'" :value="types.find((s) => s.value === slotProps.data.type)?.label || '未知'" />
                    </template>
                </Column>
                <Column field="status" header="状态" sortable style="min-width: 10rem" bodyClass="text-center">
                    <template #body="slotProps">
                        <Tag :severity="slotProps.data.status === 1 ? 'info' : 'secondary'" :value="statuses.find((s) => s.value === slotProps.data.status)?.label || '未知'" />
                    </template>
                </Column>
                <Column frozen alignFrozen="right" header="操作" :exportable="false" style="min-width: 8rem">
                    <template #body="slotProps">
                        <div class="flex gap-2">
                            <Button
                                icon="pi pi-pencil"
                                text
                                rounded
                                severity="info"
                                @click="editQuestion(slotProps.data)"
                                v-tooltip.top="'编辑题目'"
                            />
                            <Button
                                icon="pi pi-trash"
                                text
                                rounded
                                severity="danger"
                                @click="confirmDeleteQuestion(slotProps.data)"
                                v-tooltip.top="'删除题目'"
                            />
                        </div>
                    </template>
                </Column>
            </DataTable>
        </div>

        <!-- 删除确认对话框 -->
        <Dialog v-model:visible="deleteQuestionDialog" :style="{ width: '450px' }" header="确认删除" :modal="true">
            <div class="flex items-center gap-4">
                <i class="pi pi-exclamation-triangle !text-3xl" />
                <span v-if="question"
                    >确定要删除题目 <b>{{ question.code }}</b> 吗？</span
                >
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="deleteQuestionDialog = false" />
                <Button label="确定" icon="pi pi-check" severity="danger" @click="deleteQuestion" />
            </template>
        </Dialog>

        <!-- 批量删除确认对话框 -->
        <Dialog v-model:visible="deleteQuestionsDialog" :style="{ width: '450px' }" header="确认删除" :modal="true">
            <div class="flex items-center gap-4">
                <i class="pi pi-exclamation-triangle !text-3xl" />
                <span>确定要删除选中的题目吗？</span>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="deleteQuestionsDialog = false" />
                <Button label="确定" icon="pi pi-check" severity="danger" @click="deleteSelectedQuestions" />
            </template>
        </Dialog>
    </div>
</template>

<style scoped>
.text-truncate {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
</style>
